package com.taogewan.widget;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taogewan.utils.GlobalUtils;

public class AliPayHomeActivity extends AppCompatActivity {

    private View view_toolbar;
    private View cl_parallax;
    private LinearLayout ll_category1;
    private LinearLayout ll_category2;
    private ImageView iv_image;
    private NestedScrollView nsv_scroll;
    private LinearLayout ll_offset;
    private TextView tv_refresh;

    private float m_density;
    private int m_offset = 0;
    private int m_scroll_y = 0;
    private float y1 = 0;// 手指按下时的位置
    private float y2 = 0;// 手指偏移时的位置
    private float y3 = 0;// 手指偏移时的位置

    private int lastScrollY = 0;
    private int hCategory1 = 0;// ll_category1高度
    private int hParallax = 0;// 顶部偏移高度
    private int hToolbar = 0;// toolbar高
    private int hScrollParallax = 0;// 顶部滚动隐藏距离

    private int pullDamp = 2;// 下拉阻尼
    private int refreshableDistance = GlobalUtils.dp2px(60);// 下拉可刷新距离
//    private int refreshSuccess = 1;// 刷新成功
//    private int refreshFail = 0;// 刷新失败
    private int refreshNoTrigger = 0;// 未到达下拉刷新距离
    private int refreshing = 1;// 正在刷新
    private int toRefresh = 2;// 松手去刷新
    private int refreshState = refreshNoTrigger;// 下拉刷新状态， 用户松手后根据该值判断是否需要执行刷新操作

    private float endPosition = 0;// 下拉最后的位置
    private int millisInFuture = 150;// 倒计时多久
    private int countDownInterval = 10;// 倒计时速度
    private int positionDistance = millisInFuture / countDownInterval;// 移动距离

    private float quickScrollDistance = 0;// 手指点击抬起偏移量;

    private MotionEvent m_event;

    private float position = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ali_pay_home);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        m_density = dm.density;

        initView();
    }

    private void initView() {
        view_toolbar = findViewById(R.id.view_toolbar);
        cl_parallax = findViewById(R.id.cl_parallax);
        ll_category1 = findViewById(R.id.ll_category1);
        ll_category2 = findViewById(R.id.ll_category2);
        iv_image = findViewById(R.id.iv_image);
        nsv_scroll = findViewById(R.id.nsv_scroll);
        ll_offset = findViewById(R.id.ll_offset);
        tv_refresh = findViewById(R.id.tv_refresh);
    }

    private void initData() {
        position = ll_offset.getTranslationY();
        hCategory1 = ll_category1.getMeasuredHeight();
        hParallax = cl_parallax.getMeasuredHeight() + ll_category2.getMeasuredHeight();
        hToolbar = view_toolbar.getMeasuredHeight();
        hScrollParallax = hParallax - hToolbar;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        initData();
        initListener();
    }

    private void initListener() {
        nsv_scroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (lastScrollY < hScrollParallax) {
                    scrollY = Math.min(hScrollParallax, scrollY);
                    m_scroll_y = scrollY > hScrollParallax ? hScrollParallax : scrollY;
                    cl_parallax.setTranslationY((m_offset - m_scroll_y) / 2);
                    ll_category2.setTranslationY(m_offset - m_scroll_y);
                }

                if(scrollY <= hCategory1) {
                    float alpha = 1 - (float) scrollY / hCategory1;
                    ll_category1.setAlpha(alpha);
                }

                if(scrollY >= hCategory1) {
                    view_toolbar.setAlpha(1.0f);
                }else {
                    view_toolbar.setAlpha(0);
                }

                if(scrollY == 0) {
                    y1 = m_event.getY();
//                    Log.d("ACTION_UP_SCROLL", "y2:" + y2 + "-y3" + y3 +"=quick_scroll_distance:" + quick_scroll_distance);
                    if(quickScrollDistance > 0) {
                        timer2.start();
                    }
                }

                lastScrollY = scrollY;

//                Log.d("ACTION_UP_SCROLL", "scrollY:" + scrollY + "  oldScrollY:" + oldScrollY + "  lastScrollY:" + lastScrollY + "  quick_scroll_distance:" + quick_scroll_distance);
            }
        });

        nsv_scroll.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(refreshState == refreshing) {
                    return true;
                }

                m_event = event;
                //继承了Activity的onTouchEvent方法，直接监听点击事件
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
                    //当手指按下的时候记录手指点击的坐标
                    y1 = event.getY();
                    y3 = event.getY();
                    setRefreshTips(R.string.pull_to_refresh);// 展示下拉提示内容
                }
                if(event.getAction() == MotionEvent.ACTION_UP) {
                    y2 = event.getY();
                    //当手指离开的时候根据refreshState的状态判断是否需要执行刷新方法
                    if(refreshState == toRefresh) {
                        setRefreshTips(R.string.is_refreshing);
                        refreshState = refreshing;
                        ll_offset.setTranslationY(position + refreshableDistance);
                        new Handler().postDelayed(runnable, 3000);
                    }else {
                        // 根据拖拽距离判断是否需要执行收缩方法
                        if(ll_offset.getTranslationY() > position) {
                            endPosition = ll_offset.getTranslationY();
                            timer.start();
                        }
                    }

                    quickScrollDistance = y2 - y3;

//                    Log.d("quick_scroll_distance", "y2:" + y2 + "-y3" + y3 +"=quick_scroll_distance:" + quick_scroll_distance);
                }
                if(event.getAction() == MotionEvent.ACTION_MOVE) {
                    //当手指离开的时候
                    y2 = event.getY();

                    // 当nsv_scroll移动到顶部，并且y2 - y1 > 0(表示用户正在下拉)
                    if(y2 - y1 > 0 && nsv_scroll.getScrollY() == 0) {
                        // 下拉距离大于可刷新距离
                        if((int)((y2 - y1) / pullDamp) > refreshableDistance) {
                            refreshState = toRefresh;
                            setRefreshTips(R.string.loosen_refresh);
                        }else {
                            refreshState = refreshNoTrigger;
                            setRefreshTips(R.string.pull_to_refresh);
                        }
                        float py = y2 - y1;
                        ll_offset.setTranslationY(py / pullDamp);// 移动布局
                        return true;
                    }
                    if(y1 - y2 >0) {
                        y3 = Math.min(y3, y2);
                    }

                }
                return false;
            }
        });
    }

    private void setRefreshTips(int tips) {
        if(refreshState == refreshing) {
            return;
        }
        tv_refresh.setText(tips);
    }

    CountDownTimer timer = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {
            float pyl = (endPosition - position) / positionDistance;
            ll_offset.setTranslationY(ll_offset.getTranslationY() - pyl);
        }
        @Override
        public void onFinish() {
            ll_offset.setTranslationY(position);
            refreshState = refreshNoTrigger;
        }
    };

    CountDownTimer timer2 = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {
            float pyl = quickScrollDistance / positionDistance;
            ll_offset.setTranslationY(ll_offset.getTranslationY() + pyl);
        }
        @Override
        public void onFinish() {
            endPosition = ll_offset.getTranslationY();
            timer.start();
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            refreshState = toRefresh;
            endPosition = ll_offset.getTranslationY();
            timer.start();
            setRefreshTips(R.string.refresh_success);
        }
    };

}
